package m202405.d21;

/**
 * @@author: 爱做梦的锤子
 * @date: 2024/5/21 18:39
 */
public class Q41 {

    public static void main(String[] args) {
        Q41 q41 = new Q41();
        q41.firstMissingPositive(new int[]{2, 1});
    }

    public int firstMissingPositive(int[] nums) {
        for (int i = 0; i < nums.length; ) {
            if (nums[i] <= 0 || nums[i] > nums.length || nums[i] == i + 1) {
                i++;
                continue;
            }
            int temp = nums[i];
            swap(nums, i, nums[i] - 1);
            if (temp == nums[i]) {
                i++;
            }
        }
        for (int i = 0; i < nums.length; i++) {
            if (nums[i] != i + 1) {
                return i + 1;
            }
        }
        return nums[nums.length - 1] + 1;
    }


    private void swap(int[] nums, int i, int j) {
        int temp = nums[i];
        nums[i] = nums[j];
        nums[j] = temp;
    }
}
